package cn.texous.web.parsing.book.service.impl.mysql;

import cn.texous.util.commons.exception.BusinessException;
import cn.texous.util.commons.util.ConverterUtils;
import cn.texous.util.commons.util.Md5Util;
import cn.texous.util.commons.util.StringUtils;
import cn.texous.web.parsing.book.common.constants.AnaDefaultHeaderEnum;
import cn.texous.web.parsing.book.common.constants.AnaResultCode;
import cn.texous.web.parsing.book.common.constants.NormalStatusEnum;
import cn.texous.web.parsing.book.config.mysql.AbstractService;
import cn.texous.web.parsing.book.dao.mysql.AnaUserMapper;
import cn.texous.web.parsing.book.manager.RedisManager;
import cn.texous.web.parsing.book.manager.UserManager;
import cn.texous.web.parsing.book.model.entity.mysql.AnaUser;
import cn.texous.web.parsing.book.model.param.AnaUserLoginParam;
import cn.texous.web.parsing.book.model.param.AnaUserRegisterParam;
import cn.texous.web.parsing.book.service.api.mysql.AnaUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * insert description here.
 *
 * @author Showa.L
 * @since 2020-03-11 14:20:37
 */
@Service
public class AnaUserServiceImpl
        extends AbstractService<AnaUser> implements AnaUserService {

    @Resource
    private AnaUserMapper anaUserMapper;

    @Override
    public Integer register(AnaUserRegisterParam param) {
        if (anaUserMapper.existsWithPhoneNumber(param.getPhoneNumber()) > 0)
            throw new BusinessException(AnaResultCode.ANA_USER_EXISTS_ERROR);

        AnaUser anaUser = ConverterUtils.convert(AnaUser.class, param);
        if (StringUtils.isTrimEmpty(anaUser.getHeadImg()))
            anaUser.setHeadImg(AnaDefaultHeaderEnum.BIRD.getUrl());
        // 暂时不做用户名，用户名和手机号相同
        anaUser.setUsername(anaUser.getPhoneNumber());
        anaUser.setPassword(Md5Util.md5Hex(anaUser.getPassword()));
        anaUser.setStatus(NormalStatusEnum.AVAILABLE.getCode());
        anaUserMapper.insertSelective(anaUser);
        return anaUser.getId();
    }

    @Override
    public String login(AnaUserLoginParam param) {
        AnaUser anaUser = anaUserMapper.selectByPhoneNumber(param.getPhoneNumber());
        if (anaUser == null)
            throw new BusinessException(AnaResultCode.ANA_USER_NOT_EXISTS_ERROR);
        String pass = Md5Util.md5Hex(param.getPassword());
        if (!anaUser.getPassword().equals(pass))
            throw new BusinessException(AnaResultCode.USERNAME_OR_PWD__ERROR);
        String token = RedisManager.userLogin(anaUser);
        return token;
    }
}
